import { mitt } from "@/utils/mitt"
export default {
  data() {
    return {
      rafLastTime: null
    }
  },
  methods: {
    useParent(name) {
      let parent = this.$parent
      let parentName = parent.$options.name
      while (parentName !== name) {
        parent = parent.$parent
        if (!parent) return null
        parentName = parent.$options.name
      }
      return parent
    },
    useRequestAnimationFrame(callback = () => {}) {
      const currTime = new Date().getTime()
      const timeToCall = Math.max(0, 16 - (currTime - this.rafLastTime))
      const id = setTimeout(() => {
        callback(currTime + timeToCall)
      }, timeToCall)
      this.rafLastTime = currTime + timeToCall
      return id
    },
    useCancelRequestAnimationFrame(id) {
      clearTimeout(id)
    },
    useRect(selector, all) {
      return new Promise((resolve) => {
        uni
          .createSelectorQuery()
          .in(this)
          [all ? "selectAll" : "select"](selector)
          .boundingClientRect((rect) => {
            if (all && Array.isArray(rect) && rect.length) {
              resolve(rect)
            }
            if (!all && rect) {
              resolve(rect)
            }
          })
          .exec()
      })
    },
    // 使用监听事件
    useOnEvent(name, fun = () => {}) {
      return mitt.on(`_event_${name}`, fun)
    },
    // 取消监听事件
    useOffEvent(name) {
      return mitt.off(`_event_${name}`)
    }
  }
}
